package com.wnhz.work.yz.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.MultipleSelectAdapter;
import com.wnhz.work.yz.bean.ClassifyDetilsBean;
import com.wnhz.work.yz.bean.Fragment1Bean;
import com.wnhz.work.yz.bean.SkyIdBean;
import com.wnhz.work.yz.utils.DisplayUtil;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.Tag;
import com.wnhz.work.yz.view.TagListView;
import com.wnhz.work.yz.view.TagView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ---加入购物车弹出页面
 */
public class MultipleSelectActivity extends Activity implements View.OnClickListener, MultipleSelectAdapter.tagListView {

    public ImageOptions headoptions = new ImageOptions.Builder()
            //设置加载过程中的图片
            .setLoadingDrawableId(R.mipmap.ic_member_a)
            .setRadius(4)
            //设置加载失败后的图片
            .setFailureDrawableId(R.mipmap.ic_member_a)
            //设置使用缓存
            .setUseMemCache(true)
            //设置显示圆形图片
            .setCircular(true)
            //设置支持gif
            .setIgnoreGif(false)
            .build();

    private TagListView color_tagview;
    private TagListView standard_tagview;
    private List<Tag> colortagList = new ArrayList<Tag>();
    private List<Tag> standard_tagList = new ArrayList<>();
    private View max_lay;
    private ImageView shopping_img;
    private TextView tv_price;
    private EditText shopping_number;
    private TextView tv_store;
    private List<ClassifyDetilsBean> skuList;
    private Fragment1Bean bean;
    private ArrayList<Fragment1Bean> beanList;
    private int colorTag;
    private int standardTag;
    private String key;
    private ListView my_listView;
    private MultipleSelectAdapter adapter;
    private Button btn;
    private RelativeLayout rl_numbers;
    private String bannerUrl;

    private String image;
    private String img;
    private String store;
    private String sku_attr;
    private String price;
    private String goodsId;
    private String skuId;
    private String skuInfo;
    private String from;
    private String imghead;
    private ArrayList<SkyIdBean> skusList1 = new ArrayList<>();
    private ArrayList<SkyIdBean> skusList2 = new ArrayList<>();
    private int getTag;
    private Map<String, String> map1 = new HashMap<>();
    private List<Integer> valueList = new ArrayList<>();
    private String skuAttr;
    private BubbleSort bs = new BubbleSort();
    private String fromprice;
    private int standNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multiple_select);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        shopping_img = (ImageView) findViewById(R.id.shopping_img);

        rl_numbers = (RelativeLayout) findViewById(R.id.rl_numbers);
        tv_store = (TextView) findViewById(R.id.tv_store);
        tv_price = (TextView) findViewById(R.id.tv_price);
        btn = (Button) findViewById(R.id.btn);



        max_lay = findViewById(R.id.max_lay);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) max_lay.getLayoutParams();
        params.height = (int) (MyApplication.getInstance().window_h * 0.6);
        max_lay.setLayoutParams(params);
        findViewById(R.id.btn).setOnClickListener(this);
        findViewById(R.id.activity_multiple_select).setOnClickListener(this);
        findViewById(R.id.max_lay).setOnClickListener(this);
        findViewById(R.id.ll_add).setOnClickListener(this);//加
        findViewById(R.id.reduce).setOnClickListener(this);//减
        shopping_number = (EditText) findViewById(R.id.shopping_number);

        shopping_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    num = Integer.parseInt(s.toString());
                } catch (Exception e) {
                    num = 1;
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        my_listView = (ListView) findViewById(R.id.my_listView);

        initData();
        if ("ReplaceActivity".equals(from)) {
//            tv_store.setText("库存" + bean.getStore() + "件");
        } else if ("AddedWashActivity".equals(from)) {

        } else {
            DecimalFormat df = new DecimalFormat("######0.00");
            /*try {
                Log.e("----", MyApplication.getInstance().getUserBean().getRatio() + "");
                tv_price.setText("¥ " + df.format(Double.parseDouble(bean.getPrice()) * Double.parseDouble(MyApplication.getInstance().getUserBean().getRatio().toString())));
            } catch (Exception e) {*/
            Log.e("----", df.format(Double.parseDouble(bean.getPrice())));
            if (bean.getSkuattr() != null) {
                tv_price.setText("¥ " + df.format(Double.parseDouble(bean.getSkuattr().get(0).getPrice())));
                Log.e("价格2", "" +df.format(Double.parseDouble(bean.getSkuattr().get(0).getPrice())));
            } else {
                tv_price.setText("¥ " + df.format(Double.parseDouble(bean.getPrice())));
                Log.e("价格2", "" +df.format(Double.parseDouble(bean.getPrice())));
            }
//            }
            tv_store.setText("库存" + bean.getStore() + "件");

            if (bean.getSkuattr() != null) {
                img = skusList1.get(0).getImg();
                x.image().bind(shopping_img, img);
                rl_numbers.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initData() {
        goodsId = getIntent().getStringExtra("goodsId");
        from = getIntent().getStringExtra("from");
        imghead = getIntent().getStringExtra("img");
        bannerUrl = getIntent().getStringExtra("imgUrl");
        fromprice = getIntent().getStringExtra("price");
        x.image().bind(shopping_img, bannerUrl);

        if ("ReplaceActivity".equals(from)) {
            x.image().bind(shopping_img, imghead);
            btn.setText("替换");
            rl_numbers.setVisibility(View.GONE);
            upload();
        } else if ("AddedWashActivity".equals(from)) {
            x.image().bind(shopping_img, imghead);
            btn.setText("新增");
            rl_numbers.setVisibility(View.GONE);
            upload();
        } else {
            skuList = (List<ClassifyDetilsBean>) getIntent().getSerializableExtra("sku");
            beanList = (ArrayList<Fragment1Bean>) getIntent().getSerializableExtra("beanList");
            bean = (Fragment1Bean) getIntent().getSerializableExtra("bean");
            skusList1.clear();
            if (bean != null && bean.getSkuattr() != null) {
                skusList1.addAll(bean.getSkuattr());
                for(int i = 0;i < bean.getSkuattr().size();i++){
                    skusList2.add(bean.getSkuattr().get(i));
                }



                adapter = new MultipleSelectAdapter(MultipleSelectActivity.this, skuList);
                my_listView.setAdapter(adapter);

                map1 = adapter.getSkuAttr();

                adapter.setTagClick(new MultipleSelectAdapter.tagListView() {
                    @Override
                    public void onClick(int position, int index, TagView tagView, List<Tag> tagList, Tag tag, TagListView tlv_tagview) {

                        Log.e("==我的点击位置==", position + " ==下标 index== " + index);
                        for (int i = 0; i < tagList.size(); i++) {
                            if (tag.getId() == tagList.get(i).getId()) {
                                getTag = tagList.get(i).getId();
                                map1.put(position + "", getTag + "");
                                TagView view = (TagView) tlv_tagview.getChildAt(i);
                                view.setBackgroundDrawable(pitchOnColor(getResources().getColor(R.color.main_color), getResources().getColor(R.color.main_color)));
                                view.setTextColor(getResources().getColor(R.color.white));
                                tagList.get(i).setChecked(true);
                            } else {
                                TagView view = (TagView) tlv_tagview.getChildAt(i);
                                view.setBackgroundDrawable(pitchOnColor(getResources().getColor(R.color.white), getResources().getColor(R.color.text)));
                                view.setTextColor(getResources().getColor(R.color.text));
                                tagList.get(i).setChecked(false);
                                //修改
//                                    if (map1.containsKey(position + "")) {
//                                        map1.remove(position + "");
//                                    }
                            }
                        }
                        for (String key : map1.keySet()) {
                            Log.e("==onClick==", "-----"+key+"   "+map1.get(key)+"---");
                        }
                        FindData();
                    }
                });

                adapter.notifyDataSetChanged();

            }
            btn.setText("加入购物车");


//            upload();
        }
    }

    private void upload() {
        showDialog();
        final Map<String, Object> map = new HashMap<>();
        if (MyApplication.getInstance().getUserBean() != null && MyApplication.getInstance().getUserBean().getToken() != null && !MyApplication.getInstance().getUserBean().getToken().equals("")) {

        } else {
            MyToast("请登录");
            startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
            return;
        }
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("goodsId", goodsId);
        XUtil.Post(Url.PACKAGE_GETGOODSSKU, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("====================", "onSuccess:GETGOODSSKU= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    Fragment1Bean bean = new Fragment1Bean();
                    Gson gson = new Gson();
                    bean = gson.fromJson(jsonObject.optString("info"), Fragment1Bean.class);
                    skusList2.clear();

                    JSONObject jsonObject1 = jsonObject.optJSONObject("info");
                    JSONObject jsonObject2 = jsonObject1.optJSONObject("sku_attr");

                    Iterator iterator = jsonObject2.keys();                       // jsonObject2是JSONObject对象
                    while (iterator.hasNext()) {
                        String key = iterator.next() + "";
                        String v = jsonObject2.optString(key);
                        SkyIdBean skuBean = new SkyIdBean();
                        skuBean = gson.fromJson(v, SkyIdBean.class);
                        skuBean.setKey(key);
                        Log.e("===sku的 key值==", "onSuccess:sku_attr_key = =" + key);
                        skusList2.add(skuBean);
                    }

                    bean.setSkuattr(skusList2);
                    skuList = new ArrayList<>();
                    skuList.clear();
                    skuList = bean.getSku();

                    tv_price.setText("¥ " + skusList2.get(0).getPrice());
                    Log.e("价格1", "" +bean.getSku());
                    tv_store.setText("库存" + skusList2.get(0).getStore() + "件");

                    Log.e("====选择sku==========", "" + skuList.size());

                    adapter = new MultipleSelectAdapter(MultipleSelectActivity.this, skuList);
                    my_listView.setAdapter(adapter);

                    map1 = adapter.getSkuAttr();

                    adapter.setTagClick(new MultipleSelectAdapter.tagListView() {
                        @Override
                        public void onClick(int position, int index, TagView tagView, List<Tag> tagList, Tag tag, TagListView tlv_tagview) {

                            Log.e("==我的点击位置==", position + " ==下标 index== " + index);
                            for (int i = 0; i < tagList.size(); i++) {
                                if (tag.getId() == tagList.get(i).getId()) {
                                    getTag = tagList.get(i).getId();
                                    map1.put(position + "", getTag + "");
                                    TagView view = (TagView) tlv_tagview.getChildAt(i);
                                    view.setBackgroundDrawable(pitchOnColor(getResources().getColor(R.color.main_color), getResources().getColor(R.color.main_color)));
                                    view.setTextColor(getResources().getColor(R.color.white));
                                    tagList.get(i).setChecked(true);
                                } else {
                                    TagView view = (TagView) tlv_tagview.getChildAt(i);
                                    view.setBackgroundDrawable(pitchOnColor(getResources().getColor(R.color.white), getResources().getColor(R.color.text)));
                                    view.setTextColor(getResources().getColor(R.color.text));
                                    tagList.get(i).setChecked(false);
                                    //修改
//                                    if (map1.containsKey(position + "")) {
//                                        map1.remove(position + "");
//                                    }
                                }
                            }
                            for (String key : map1.keySet()) {
                                Log.e("==onClick==", "-----"+key+"   "+map1.get(key)+"---");
                            }
                          FindData();
                        }
                    });

                    adapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private void FindData() {
        Log.e("--选择的sku属性 FindData ===", "进来了");
        valueList.clear();
        for (Map.Entry<String, String> entry : map1.entrySet()) {
            valueList.add(Integer.valueOf(entry.getValue()));
        }
        bs.bubble(valueList);
        MultipleSelectActivity.this.skuAttr = "-";
        for (int i1 = 0; i1 < valueList.size(); i1++) {
            MultipleSelectActivity.this.skuAttr = MultipleSelectActivity.this.skuAttr + valueList.get(i1) + "-";
        }

        Log.e("--选择的sku属性===", MultipleSelectActivity.this.skuAttr);

        for (int i1 = 0; i1 < skusList2.size(); i1++) {
            if (MultipleSelectActivity.this.skuAttr.equals(skusList2.get(i1).getKey())) {
                Log.e("--选择的sku属性 的skuId===", "进来了");
                skuId = skusList2.get(i1).getSku_id();
                store = skusList2.get(i1).getStore();
                image = skusList2.get(i1).getImg();
                price = skusList2.get(i1).getPrice();
                skuInfo = skusList2.get(i1).getSku_info();
                tv_store.setText("库存" + store + "件");
                DecimalFormat df = new DecimalFormat("######0.00");
                /*try {
//                                            Log.e("----", MyApplication.getInstance().getUserBean().getRatio() + "");
                    tv_price.setText("¥ " + df.format(Double.parseDouble(skusList2.get(i1).getPrice()) * Double.parseDouble(MyApplication.getInstance().getUserBean().getRatio().toString())));
                } catch (Exception e) {*/
//                                            Log.e("----", df.format(Double.parseDouble(skusList2.get(i1).getPrice()) * 1.2));
                final Map<String, Object> maps = new HashMap<>();
               // maps.put("goodsPrice", price);
//                tv_price.setText("¥ "+price);
//                Log.e("--价格===", price);
                //价格
                //df.format(Double.parseDouble(bean1.getOprice()
                tv_price.setText("¥ " + df.format(Double.parseDouble(skusList2.get(i1).getPrice())));
//                }
                x.image().bind(shopping_img, image);

                if ("0".equals(store)) {
                    MyToast("没有库存了！");
                }
                break;
            }
        }
    }


    private GradientDrawable pitchOnColor(int color1, int color2) {
        GradientDrawable gd = new GradientDrawable();
        int strokeWidth = DisplayUtil.dp2px(this, 0.5f);//边框宽度
        //int roundRadius = DensityUtils.dp2px(this, 25); // 8dp 圆角半径
        gd.setCornerRadius(DisplayUtil.dp2px(this, 4));
        gd.setColor(color1);
        //gd.setCornerRadius(roundRadius);
        gd.setStroke(strokeWidth, color2);
        return gd;
    }

    private int num = 1;

    @Override
    public void onClick(View v) {

        Intent intent;
        switch (v.getId()) {
            //父布局
            case R.id.activity_multiple_select:
                finish();
                overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
                break;

            //子布局
            case R.id.max_lay:
                break;

            //加
            case R.id.ll_add:
                num += 1;
                shopping_number.setText(num + "");
                break;

            //减
            case R.id.reduce:
                if (num > 1) {
                    num -= 1;
                    shopping_number.setText(num + "");
                } else {
                    MyToast("再减就没了");
                }
                break;

            case R.id.btn:
                if (MyApplication.getInstance().getUserBean() != null) {

                    //对比找出的选择的sku
                    FindData();

                    if ("ReplaceActivity".equals(from)) {
                        Log.e("==替换 ReplaceActivity==", " 进来 ");
                        if (skuList == null) {
                            MyToast("暂无sku套餐");
                            return;
                        }

                        int standNum = 0;
                        StringBuffer stringBuffer = new StringBuffer();
                        ArrayList<String> keys = new ArrayList<>();
                        for (String key : map1.keySet()) {
                            //  stringBuffer.append("-" + map1.get(key));
                            keys.add(key);
                        }
                        int a = pattern(skusList2.get(0).getKey(), "-");
                        if (a == 4) {
                            for (String key : map1.keySet()) {
                                stringBuffer.append("-" + map1.get(key));
                            }
                        } else {
                            for (int i = keys.size() - 1; i >= 0; i--) {
                                stringBuffer.append("-" + map1.get(keys.get(i)));
                            }
                        }
                        for (int i = 0; i < skusList2.size(); i++) {
                            Log.e("==替换 ReplaceActivity==", " 选择不同2 ");
                            if (skusList2.get(i).getKey().contains(stringBuffer.toString())) {
                                Log.e("==替换 ReplaceActivity==", skusList2.get(i).getKey());
                                if (skusList2 == null || skusList2.get(i) == null || skusList2.get(i).getSku_info() == null) {

                                    return;
                                }
                                int  store=0;
                                try {
                                    store=Integer.valueOf(  skusList2.get(i).getStore());
                                    Log.e("==库存==", store+"");
                                }catch (Exception e){}

                                if (store<1) {//ku c xiaoyu 1
                                    standNum++;
                                }

                            }
                        }

                        if (standNum > 0) {
                            MyToast("暂无此搭配商品");
                            return;
                        }
                        for (String key : map1.keySet()) {
                            Log.e("==map1==", key+"   "+map1.get(key));
                            //  stringBuffer.append("-" + map1.get(key));
                    //        keys.add(key);
                        }

                        if (map1.size() == skuList.size()) {
                            intent = new Intent(this, ReplaceActivity.class);
                            intent.putExtra("price", price);
                            intent.putExtra("img", image);
                            intent.putExtra("skuInfo", skuInfo);
                            intent.putExtra("skuId", skuId);
                            intent.putExtra("isold", "2");
                            setResult(RESULT_OK, intent);
                            finish();
                        } else {
                            MyToast("请选择完整套餐信息");
                        }
                    } else if ("AddedWashActivity".equals(from)) {
                        Log.e("==新增AddedWashActivity==", " 进来 ");
                        if (null != map1 && null != skuList) {
                            if (map1.size() == skuList.size()) {
                                intent = new Intent(this, AddedWashActivity.class);

                                intent.putExtra("price", price);
                                intent.putExtra("img", image);
                                intent.putExtra("skuInfo", skuInfo);
                                intent.putExtra("skuId", skuId);
                                intent.putExtra("isold", "2");
                                //                            Log.e("==新增AddedWashActivity==", " 进来 price=" + price + " = skuInfo=" + skuInfo + " = image=" + image + " = skuId= " + skuId);
                                setResult(RESULT_OK, intent);
                                finish();
                            } else {
                                MyToast("请选择完整套餐信息");
                            }
                        }
                    } else {

                        addCard();
                    }
                } else {
                    intent = new Intent(this, LoginFirstActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    public void finish() {
        super.finish();
        // overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
    }

    private static final String TAG = "MultipleSelectActivity";

    private void addCard() {
        showDialog();
        String goodsNum = shopping_number.getText().toString();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("goodsId", goodsId);
        map.put("skuId", skuId);

        map.put("nums", goodsNum);
        Log.i(TAG, "addCard: skuId= " + goodsId);
        Log.i(TAG, "addCard: skuId= " + skuId);
        Log.i(TAG, "addCard: skuId= " + goodsNum);
        XUtil.Post(Url.ADDTOCART, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i(TAG, "onSuccess:skuId= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        MyToast(info);
                        finish();
                    } else {
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private Toast toast;

    public void MyToast(String s) {
        if (toast == null)
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        else
            toast.setText(s);
        toast.show();
    }

    protected Dialog dialog;

    public void showDialog() {
    }

    public void closeDialog() {
    }

    @Override
    public void onClick(int position, int index, TagView tagView, List<Tag> tagList, Tag tag, TagListView tlv_tagview) {

    }

    /*
     * 冒泡排序
     */
    public class BubbleSort {

        public void bubble(List<Integer> data) {
            for (int i = 0; i < data.size(); i++) {
                for (int j = 0; j < data.size() - 1 - i; j++) {
                    if (data.get(j) > data.get(j + 1)) {   //如果后一个数小于前一个数交换
                        int tmp = data.get(j);
                        data.set(j, data.get(j + 1));
                        data.set(j + 1, tmp);
                    }
                }
            }
        }
    }

    private int pattern(String text, String chars) {
        // 根据指定的字符构建正则
        Pattern pattern = Pattern.compile(chars);
        // 构建字符串和正则的匹配
        Matcher matcher = pattern.matcher(text);
        int count = 0;
        // 循环依次往下匹配
        while (matcher.find()) { // 如果匹配,则数量+1
            count++;
        }
        return count;
    }

}
